package com.pine.dcts.auth.handler;


import com.pine.dcts.auth.utils.VerificationCodeUtils;
import com.pine.dcts.auth.verfivation.VerificationCodeCache;
import com.pine.dcts.common.BaseHandler;
import com.pine.dcts.common.DctsConstant;
import com.pine.dcts.common.DctsException;
import com.pine.dcts.common.Result;
import com.pine.dcts.entity.User;
import com.pine.dcts.service.UserService;
import com.pine.dcts.utils.Base64;
import com.pine.dcts.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author xiaoyuan
 * @create 2020/4/14 22:09
 **/
@RestController
@RequestMapping("/login")
@Slf4j
public class UserResourceHandler extends BaseHandler {
    @Autowired
    private VerificationCodeCache verificationCodeCache;
    @Autowired
    private UserService userService;



    @GetMapping("/vcc/image")
    public Result<Map<String,String>> validate() {
        String uuid = UUID.randomUUID().toString();
        try {
            // 生成图片
            int w = 87, h = 38;
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            String value = VerificationCodeUtils.generateVerifyCode(4);
            VerificationCodeUtils.outputImage(w, h, stream, value);
            verificationCodeCache.set(DctsConstant.VERIFICATION_CODE_CACHE_NAME, uuid, value);
            Map<String,String> result = new HashMap<>();
            result.put("vcode", Base64.encode(stream.toByteArray()));
            result.put("codeUID",uuid);
            return Result.success(result);
        } catch (IOException e) {
            log.error("生成验证码异常", e);
            throw new DctsException("验证码异常");
        }
    }
    @GetMapping("/info")
    public Result<User> getUserInfo(){
       return Result.success(userService.getByLoginName(SecurityUtils.getUsername()));
    }
}
